<template>
  <div class="goods-detail fixed-top fixed-bottom">
    <NavBar title="商品详情" fixed back/>
    <van-swipe class="goods-swipe" :autoplay="3000">
      <van-swipe-item v-for="(thumb, index) in thumbs" :key="index">
        <img :key="GLOBAL.baseImagePath + thumb.picUrl" v-lazy="GLOBAL.baseImagePath + thumb.picUrl" @click="imagePreview(index)" >
      </van-swipe-item>
    </van-swipe>

    <div class="goods-title">{{ name }}</div>
    <van-row class="goods-stock">
      <van-col span="12">商品库存：{{ stock }}</van-col>
      <van-col span="12" style="text-align: right">商品销量：{{ sales }}</van-col>
    </van-row>
    <van-cell-group class="goods-cell-group">
      <van-cell title="销售价" >
        <span class="van-cell-text">{{ formatPrice(salePrice) }}</span>
      </van-cell>
      <van-cell title="优惠价" v-if="isDiscount">
        <span class="van-cell-text">{{ formatPrice(discountPrice) }}</span>
      </van-cell>
      <van-cell title="会员价" v-if="login">
        <span class="van-cell-text">{{ formatPrice(memberPrice) }}</span>
      </van-cell>
    </van-cell-group>

    <van-cell-group class="goods-cell-group">
      <van-cell title="商品规格" >
        <span v-for="(item, index) in list" v-bind:key="index" >
          <input type="radio" name="property" :value="index" v-model="selectedIndex" />{{ item.property }}<br />
        </span>
      </van-cell>
      <div class="van-sku-stepper-stock">
        <div class="van-sku-stepper-container">
          <div class="van-sku__stepper-title" style="color: #333;font-size: 14px;">购买数量：</div>
          <div class="van-sku__stepper van-stepper">
            <van-stepper v-model="selectNum" integer :min="1" :max="stock" :step="1" @change="ckstock()" class="cart-stepper"/>
          </div>
        </div>
      </div>
    </van-cell-group>
      <van-cell-group class="goods-cell-group">
        <van-cell title="商品详情" is-link @click="toGoodsDetail"/>
        <van-cell title="查看评论" is-link @click="toComment"/>
      </van-cell-group>
    <van-goods-action>

      <van-goods-action-mini-btn :info="cartNumber" icon="cart" @click="toClickCart">
        购物车
      </van-goods-action-mini-btn>
      <van-goods-action-big-btn warning @click="addCartgoods()" :disabled="status">
        加入购物车
      </van-goods-action-big-btn>
      <van-goods-action-big-btn primary @click="purchaseImmediately()" :disabled="status">
        立即购买
      </van-goods-action-big-btn>
    </van-goods-action>
  </div>
</template>

<script>
import NavBar from '../../components/common/NavBar.vue'
import { Toast, ImagePreview, Sku } from 'vant'
import Vue from 'vue'
import detailAPI from '../../api/detail'

Vue.use(Sku)
export default {
  data () {
    return {
      status: false,
      list: [],
      thumbs: [],
      name: '',
      goodsId: 0,
      salePrice: 0,
      isDiscount: false,
      discountPrice: 0,
      memberPrice: 0,
      sales: 0,
      propertys: [],
      stock: 0,
      selectedIndex: 0,
      selectNum: '',
      login: this.$store.state.login,
      discountPoint: 0.0,
      cartNumber: 0
    }
  },
  components: {
    NavBar
  },
  watch: {
    selectedIndex (oldSelectedIndex, newSselectedIndex) {
      this.thumbs = this.list[this.selectedIndex].picUrl
      this.stock = this.list[this.selectedIndex].stock
      this.isDiscount = this.list[this.selectedIndex].isDiscount
      this.discountPrice = this.list[this.selectedIndex].discountPrice
      this.salePrice = this.list[this.selectedIndex].salePrice
      if (this.isDiscount === 1) {
        this.memberPrice = this.discountPrice * this.discountPoint
      } else {
        this.memberPrice = this.salePrice * this.discountPoint
      }
    }
  },
  methods: {
    toComment () {
      this.$router.push({path: '/comment', query: {goodsId: this.$route.query.goodsId}})
    },
    toGoodsDetail: function () {
      this.$router.push({path: '/item/goodsDetail', query: {goodsId: this.$route.query.goodsId}})
    },
    formatPrice (_price) {
      return '¥' + parseFloat(_price).toFixed(2)
    },
    ckstock () {
      let _this = this
      if (_this.selectNum >= _this.stock) {
        Toast.fail('已经是最大库存无法再添加')
      }
    },
    addCartgoods () {
      const _this = this
      let _propertyId = _this.list[this.selectedIndex].propertyId
      let _selectNum = _this.selectNum
      if (_this.selectNum < 1) {
        Toast.fail('商品数量不能为小于1')
      } else {
        detailAPI.addCartgoods(_propertyId, _selectNum).then(function (res) {
          if (res.data.status === 0) {
            Toast.success('添加购物车成功')
            _this.getCartNumber()
          } else {
            Toast.fail(res.data.msg)
          }
        })
      }
    },
    toClickCart () {
      this.$router.push('/cart')
    },
    getCartNumber () {
      const _this = this
      detailAPI.getCartNumber().then(function (res) {
        if (res.data.re > 0) {
          _this.cartNumber = res.data.re
        }
      })
    },
    purchaseImmediately () {
      let _this = this
      let list1 = []
      let proper = {
        goodsId: '',
        propertyId: '',
        num: ''
      }
      proper.propertyId = _this.list[_this.selectedIndex].propertyId
      proper.num = _this.selectNum
      detailAPI.addCartgoods(proper.propertyId, proper.num).then(function (res) {
        if (res.data.status === 0) {
          proper.goodsId = _this.goodsId
          let _totalPrice = _this.selectNum * _this.salePrice
          list1.push(proper)
          sessionStorage.setItem('goodsList', JSON.stringify(list1))
          sessionStorage.setItem('totalPrice', _totalPrice)
          _this.$router.push({path: '/cart/confirm'})
        } else {
          Toast.fail(res.data.msg)
        }
      })
    },
    initItemDetail (_goodsId) {
      const _this = this
      detailAPI.getGoodsDetailByGoodsId(_goodsId).then(function (res) {
        if (res.data.re === null || res.data.re.length === 0) {
          Toast.fail('商品已送到火星了，请重新选择')
          _this.status = true
          return false
        }
        if (res.data.re[0].status === 0 || res.data.re[0].isDelete === 1) {
          Toast.fail('商品已送到火星了，请重新选择')
          _this.status = true
          return false
        }
        _this.list = res.data.re
        let i = 0
        _this.name = _this.list[i].name
        _this.salePrice = _this.list[i].salePrice
        _this.goodsId = _this.list[i].goodsId
        if (_this.list[i].isDiscount === 1) {
          _this.isDiscount = true
          _this.discountPrice = _this.list[i].discountPrice
        }
        if (_this.list[i].sales === null) {
          _this.sales = 0
        } else {
          _this.sales = _this.list[i].sales
        }
        _this.propertys[i] = _this.list[i].property
        _this.stock = _this.list[i].stock
        _this.thumbs = _this.list[i].picUrl
        if (_this.$store.state.login === true) {
          detailAPI.getMemberDiscountPoint().then(function (res) {
            let _discountPoint = res.data.re
            _this.discountPoint = _discountPoint
            if (_this.list[_this.selectedIndex].isDiscount === 1) {
              _this.memberPrice = _this.discountPrice * _discountPoint
            } else {
              _this.memberPrice = _this.salePrice * _discountPoint
            }
          })
          _this.getCartNumber()
        }
      })
    },
    // 判断图片是否存在
    checkImgExists (imgurl) {
      let image = new Image()
      image.src = imgurl
      // 没有图片，则返回-1
      if (image.fileSize > 0 || (image.width > 0 && image.height > 0)) {
        return true
      } else {
        return false
      }
    },
    // 图片预览
    imagePreview (index) {
      let images = []
      let image
      for (let i = 0; i < this.thumbs.length; i++) {
        image = this.GLOBAL.baseImagePath + this.thumbs[i].picUrl
        if (this.checkImgExists(image)) {
          images.push(image)
        }
      }
      ImagePreview({
        images: images,
        startPosition: index
      })
    }
  },
  mounted () {
    let _goodsId = this.$route.query.goodsId
    this.initItemDetail(_goodsId)
  }
}
</script>

<style lang="less">
  .goods-detail {
    overflow: auto;
  }
  .goods-detail img {
    max-width: 100%;
  }
  .itemDetail {
    background: #fafafa;
  }
  .goods {
    padding-bottom: 50px;
    &-swipe {
      background: #fff;
      img {
        width: 100%;
        display: block;
      }
    }
    &-title {
      font-weight: 600;
      padding: 5px 10px;
      background-color: #FFF;
      font-size: 14px;
      color: #051B28;
      line-height: 20px;
      display: -webkit-box;
      -webkit-line-clamp: 2;
      -webkit-box-orient: vertical;
      -webkit-box-pack: center;
      max-height: 42px;
      overflow: hidden;
      word-break: break-all;
    }
    &-price {
      color: #f44;
    }
    &-express {
      color: #999;
      font-size: 12px;
      padding: 5px 15px;
    }
    &-cell-group {
      margin: 5px 0;
      .van-cell__value {
        color: #999;
      }
    }
    &-cell-group-add {
      margin-bottom: 100px;
    }
    &-tag {
      margin-left: 5px;
    }
  }

  .cart-stepper {
    float: left;
  }

  .cart-delete {
    float: left;
  }

  .goods-stock {
    background-color: #FFF;
    line-height: 30px;
    padding: 0 15px;
    font-size: 12px;
    color: #999;
  }
  .goods-stock span {
    text-align: center;
  }
</style>
